package com.cskaoyan.mall.controller.mall;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.mall.model.UpdateUserPwd;
import com.cskaoyan.mall.model.admin.AdminLoginBO;
import com.cskaoyan.mall.model.admin.AdminLoginVO;
import com.cskaoyan.mall.model.user.UserForUpdate;
import com.cskaoyan.mall.model.user.UserLoginVO;
import com.cskaoyan.mall.model.user.UserVOAndUserSignUpBO;
import com.cskaoyan.mall.service.UserService;
import com.cskaoyan.mall.service.UserServiceImpl;
import com.cskaoyan.mall.util.RequestBodyUtils;
import com.cskaoyan.mall.util.Result;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

import static com.cskaoyan.mall.util.RequestBodyUtils.getRequestBody;
import static com.cskaoyan.mall.util.UpdateOrAddAdminUtils.*;

/**
 * @author: jyf2000jyf
 */
@WebServlet("/api/mall/user/*")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replace(request.getContextPath() + "/api/mall/user/", "");
        if ("login".equals(op)) {
            login(request, response);
        } else if ("signup".equals(op)) {
            signUp(request, response);
        } else if ("logoutClient".equals(op)) {
            logoutClient(request, response);
        } else if ("updateUserData".equals(op)) {
            updateUserData(request, response);
        } else if("updatePwd".equals(op)){
            updatePwd(request,response);
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = getRequestBody(request);
        // 请求体 json字符串------java对象  {"email":"admin","pwd":"admin123"}
        AdminLoginBO adminLoginBO = gson.fromJson(requestBody, AdminLoginBO.class);
        // 校验
        if (StringUtils.isEmpty(adminLoginBO.getEmail()) || StringUtils.isEmpty(adminLoginBO.getPwd())) {
            Result result = new Result(10000, "用户名、密码不能为空", null);
            response.getWriter().println(gson.toJson(result));
            return;
        }
        Map<String, Object> map = userService.login(adminLoginBO);

        int code = (Integer) map.get("code");
        String nickname = (String) map.get("nickname");
        if (code == 200) {
            HttpSession session = request.getSession();
            session.setAttribute("userEmail", adminLoginBO.getEmail());
            //登录成功  {"code":0,"data":{"token":"admin","name":"admin"}}
            Result result = new Result(0, null, new UserLoginVO(0, nickname, adminLoginBO.getEmail()));
            response.getWriter().println(gson.toJson(result));
            return;
        } else if (code == 404) {
            Result result = new Result(10000, "密码不正确", null);
            response.getWriter().println(gson.toJson(result));
            return;
        } else {
            Result result = new Result(10000, "服务器繁忙", null);
            response.getWriter().println(gson.toJson(result));
        }
    }

    private void signUp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = getRequestBody(request);
        UserVOAndUserSignUpBO userVOAndUserSignUpBO = gson.fromJson(requestBody, UserVOAndUserSignUpBO.class);
        Result result;
        if (!judgeEmail(userVOAndUserSignUpBO.getEmail())) {
            result = new Result(10000, "账户正则验证未通过", null);
            response.getWriter().println(gson.toJson(result));
            return;
        }
        // 4-15位昵称
        if (!judgeNickname(userVOAndUserSignUpBO.getNickname())) {
            result = new Result(10000, "昵称正则验证未通过", null);
            response.getWriter().println(gson.toJson(result));
            return;
        }
        // 8-16位，包括大小写字母、数字和符号
        if (!judgePassword(userVOAndUserSignUpBO.getPwd())) {
            result = new Result(10000, "密码正则验证未通过", null);
            response.getWriter().println(gson.toJson(result));
            return;
        }
        // TODO judgePhone and others
        boolean status = userService.addUser(userVOAndUserSignUpBO);
        if (status) {
            HttpSession session = request.getSession();
            session.setAttribute("userEmail", userVOAndUserSignUpBO.getEmail());
            result = new Result(0, "注册成功", new UserLoginVO(0, userVOAndUserSignUpBO.getNickname(), userVOAndUserSignUpBO.getEmail()));
            response.getWriter().println(gson.toJson(result));
            return;
        } else {
            result = new Result(10000, "注册失败", null);
            response.getWriter().println(gson.toJson(result));
        }
    }

    private void updateUserData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = getRequestBody(request);
        UserForUpdate userForUpdate = gson.fromJson(requestBody, UserForUpdate.class);
        Result result;
        // 4-15位昵称
        if (!judgeNickname(userForUpdate.getNickname())) {
            result = new Result(10000, "昵称正则验证未通过", null);
            response.getWriter().println(gson.toJson(result));
            return;
        }
        boolean status = userService.updateUserData(userForUpdate);
        if (status) {
            result = new Result(0, "修改成功", null);
        } else {
            result = new Result(10000, "修改失败", null);
        }
        response.getWriter().println(gson.toJson(result));
    }

    private void updatePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = getRequestBody(request);
        UpdateUserPwd Pwd = gson.fromJson(requestBody, UpdateUserPwd.class);
        Result result;
        String returnPwd = userService.updatePwd(Pwd);
        if (returnPwd == null) {
            result = new Result(10000, "密码为空", null);
            response.getWriter().println(gson.toJson(result));
            return;
        }
        if ("确认密码和新密码不一致".equals(returnPwd) || "sql异常".equals(returnPwd) || "原密码错误".equals(returnPwd) || "密码正则验证未通过".equals(returnPwd)) {
            result = new Result(10000, returnPwd, null);
            response.getWriter().println(gson.toJson(result));
            return;
        }

        result = new Result(0, "修改密码成功", null);
        response.getWriter().println(gson.toJson(result));
    }

    private void logoutClient(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        Result result;
        if (session.getAttribute("userEmail") != null) {
            session.invalidate();
            result = new Result(0, "注销成功", null);
        } else {
            result = new Result(10000, "注销失败", null);
        }
        response.getWriter().println(gson.toJson(result));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replace(request.getContextPath() + "/api/mall/user/", "");
        if ("data".equals(op)) {
            data(request, response);
        }
    }

    private void data(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = request.getParameter("token");
        UserForUpdate user = userService.getUserByUserName(token);
        Result result = new Result(0,null,user);
        response.getWriter().println(gson.toJson(result));
    }
}
